<template>
  <div class="nav">
    <ul>
      <li><a href="#">企业信息</a></li>
      <li><a href="/#/productInfo">产品信息</a></li>
      <li><a href="/#/monitor">基地信息</a></li>
      <li><a href="#">地块信息</a></li>
      <li><a href="#">农事活动</a></li>
      <li><a href="/#/data" id="black">环境数据</a></li>
    </ul>
  </div>

  <div class="productInfo-header">
    <div class="productInfo-logo">
      <a href="/#/search"><img src="@/assets/logo1.png" alt=""></a>
    </div>
  </div>


  <div class="productInfo-content">
    <h1>云梦县公共环境数据</h1>
    <el-tabs>
      <div class="row">
        <span>查询时间</span>

        <div class="date-picker">
          <el-date-picker v-model="value" type="date" placeholder="选择日期" :size="size" @change="handleDateChange" />
          <!-- <button class="oneday" @click="fetchData('oneday')">查询<tton> -->
        </div>

        <button class="today" @click="fetchTodayData">当天</button>
        <button class="week" @click="fetchLast7DaysData">最近7天</button>
        <button class="month" @click="fetchLast30DaysData">最近30天</button>
      </div>

      <el-tab-pane label="温度">
        <!-- 插图表 -->
        <div class="temperature" ref="temperature"></div>

      </el-tab-pane>

      <el-tab-pane label="湿度">湿度</el-tab-pane>
      <el-tab-pane label="降雨量">降雨量</el-tab-pane>
    </el-tabs>





  </div>




  <div class="footer">
    <p>Copyright©2008-2023 All Rights Reserved</p>
    <p>版权所有©武汉网酷科技有限公司 | 地址：湖北省武汉市洪山区雄楚大街428号 | 邮编：430074 | 技术支持： <a href="#" title="中南民族大学工程技术中心">中南民族大学</a> <a
        href="#" title="中南民族大学工程技术中心">湖北省制造企业智能管理工程技术研究中心</a></p>
    <p><a href="#" title="鄂ICP备16008630号-1">鄂ICP备16008630号-1</a></p>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import * as echarts from "echarts";
import axios from 'axios';

const size = ref('default')

// 用ref 创建一个响应式变量来存储选中的日期
const value = ref('')
const temperature = ref()

// 用于存储从后端获取的日期数据
let xAxisData: number[] = []

window.onload = function () {
  init()
}

const handleDateChange = (selectedDate: string) => {
  value.value = selectedDate
  console.log('Selected date:', selectedDate)
  fetchData(selectedDate)
}

const init = () => {
  const myChart = echarts.init(temperature.value);
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    xAxis: [
      {
        type: 'category',
        axisTick: { alignWithLabel: true },
        data: xAxisData
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '温度',
        min: 0,
        max: 35,
        axisLabel: { formatter: '{value} °C' }
      }
    ],
    series: [{ name: '温度', type: 'line', smooth: true }]
  };
  myChart.setOption(option);
}

// 日期选择器对应的请求
const fetchData = (selectedDate: string) => {
  // 检查 selectedDate 是否为空或无效
  if (!selectedDate) {
    console.error('Invalid selected date:', selectedDate)
    return
  }
  // 格式化日期参数
  const formattedDate = new Date(selectedDate).toISOString().slice(0, 10)
  axios.get(`api/environments/queryToday?date=${formattedDate}&dataType=temperature`)
    .then(response => {
      xAxisData = response.data;
      updateChart(xAxisData);
    })
    .catch(error => {
      console.error('Error fetching temperature data:', error);
    });
}

// 点击当天、最近7天、最近30天按钮
const currentDate = new Date()
// 格式化日期参数
const formattedDate = new Date(currentDate).toISOString().slice(0, 10)

const fetchTodayData = () => {
  // console.log('Formatted date:', formattedDate);
  axios.get(`api/environments/queryToday?date=${formattedDate}&dataType=temperature`)
    .then(response => {
      xAxisData = response.data;
      updateChart(xAxisData);
    })
    .catch(error => {
      console.error('Error fetching temperature data:', error);
    });
}

const fetchLast7DaysData = () => {
  axios.get(`api/environments/querySeven?date=${formattedDate}&dataType=temperature`)
    .then(response => {
      xAxisData = response.data;
      updateChart(xAxisData);
    })
    .catch(error => {
      console.error('Error fetching temperature data:', error);
    });
}

const fetchLast30DaysData = () => {
  axios.get(`api/environments/queryToday?date=${formattedDate}&dataType=temperature`)
    .then(response => {
      xAxisData = response.data;
      updateChart(xAxisData);
    })
    .catch(error => {
      console.error('Error fetching temperature data:', error);
    });
}

const updateChart = (data: number[]) => {
  const myChart = echarts.getInstanceByDom(temperature.value);
  // 加问号，避免“可能为未定义”的错误
  myChart?.setOption({
    series: [{ data: data }]
  });
}

</script>增加一个功能：当有查询不到温度数据，仍然显示图表，没有数据的显示空值

<style>
.temperature {
  width: 900px;
  height: 450px;
  background-color: pink;
  margin: 0 auto;
}

.row {
  display: flex;
  justify-content: center;
  /* 使内容垂直居中 */
  align-items: center;
  margin-bottom: 20px;
}

.date-picker {
  display: flex;
  width: 400px;
  padding: 0;
  margin-left: 30px;
  flex-wrap: wrap;
}

.row button {
  font-size: 13px;
  background-color: #d42a19;
  color: #fff;
  border-radius: 4px;
  margin: 0 4px;
  padding: 2px 4px;
}

.row .today {
  margin-left: 100px;
}
</style>